package com.example.netty.service;

import com.alibaba.fastjson.JSON;
import com.example.netty.common.Message;
import com.example.netty.constant.ResMessageType;
import com.example.netty.dao.UserDao;
import com.example.netty.vo.Room;
import com.example.netty.vo.Shoe;
import com.example.netty.vo.User;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 游戏服务类
 * @author zclever <304078606@qq.com>
 * @date 2021-03-02
 */
@Component
public class GameService {

    private static final Logger logger = LoggerFactory.getLogger(GameService.class);

    /** 用户列表 */
    private final static ConcurrentHashMap<Channel, User> userOnline = new ConcurrentHashMap<>();
    private final static ConcurrentHashMap<User, Channel> userChannel = new ConcurrentHashMap<>();

    @Autowired
    private MatchService matchService;

    @Autowired
    private UserDao userDao;

    /**
     * 用户进入游戏
     * @param channel
     * @param content
     */
    public Message inGame(Channel channel, Object content){
        logger.info("处理进入游戏");

        //处理进入游戏
        Map map = JSON.parseObject(String.valueOf(content), Map.class);
        int userId = Integer.parseInt(String.valueOf(map.get("userId")));
        User user = userDao.get(userId);
        userOnline.put(channel,user);
        userChannel.put(user,channel);

        //返回进入成功
        logger.info("返回进入游戏");
        return new Message(ResMessageType.inGame);
    }

    /**
     * 用户退出游戏
     * @param channel
     * @return
     */
    public Message outGame(Channel channel) {
        logger.info("处理退出游戏");

        //删除在线用户,用户频道和用户匹配队列
        User user = userOnline.get(channel);
        delUserByChannel(channel);
        delChannelByUser(user);
        matchService.removeUserMatch(user);

        //返回退出成功
        logger.info("返回退出成功");
        return new Message(ResMessageType.outGame);
    }

    public User getUserByChannel(Channel channel){
        return userOnline.get(channel);
    }

    public Channel getChannelByUser(User user){
        return userChannel.get(user);
    }

    public void delUserByChannel(Channel channel){
        userOnline.remove(channel);
    }

    public void delChannelByUser(User user){
        if(user!=null)userOnline.remove(user);
    }

}
